<template>
    <div class="wrap">
        <div id="container">
            <!-- 定义一个表格元素 -->
            <!--<button id="redraw">更换数据源</button>-->
            <section class="detail-header">
                <div class="col-sm-12 console-title">
                    <h5 class="">站点监控</h5>
                    <div class="stayRight ">
                        <el-button @click="siteconfList(1,'refresh')" icon="star-off">刷新</el-button>
                        <el-button type="primary" @click="showMonitor()">创建监控点</el-button>
                    </div>

                </div>
            </section>
            <section class="searchBar">
                <div class="form-inline">
                    <div class="pull-left">
                        <div class="searchSel">
                            <el-select v-model="tpvalue" placeholder="全部类型" @change="siteconfList(1,tpvalue)">
                                <el-option v-for="item in typeMonitorOptions" :key="item.tpvalue" :label="item.label" :value="item.tpvalue">
                                </el-option>
                            </el-select>
                        </div>
                        <div class="searchIpt">
                            <el-input v-model="addrinput" placeholder="监控地址"></el-input>
                        </div>
                        <div class="searchIpt">
                            <el-input v-model="projectName" placeholder="项目名称"></el-input>
                        </div>
                        <div class="searchbtn">
                            <el-button @click="siteconfList(1,tpvalue,addrinput,projectName,10)">搜索</el-button>
                        </div>
                    </div>
                </div>
            </section>
            <section class="tableMain">
                <el-table :data="dataArr" border style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column prop="projectName" label="项目名称" > </el-table-column>
                    <el-table-column prop="name" label="监控点名称" > </el-table-column>
                    <el-table-column prop="address" label="监控地址" > </el-table-column>
                    <el-table-column prop="type" label="类型" > </el-table-column>
                    <el-table-column prop="toUser" label="通知对象" > </el-table-column>
                    <el-table-column prop="principal" label="负责人" > </el-table-column>
                    <el-table-column label="监控频率" ><template scope="scope">{{ scope.row.frequency }} 分钟</template> </el-table-column>
                    <el-table-column label="状态"> 
                    	<template scope="scope">
                    		<el-tag size="small" :type="scope.row.status === '正常' ? 'success' : scope.row.status === '异常' ? 'danger' : 'info'" close-transition>{{scope.row.status}}</el-tag>
                    	</template> 
                    </el-table-column>
                    <el-table-column label="操作">
                        <template scope="scope">
                            <el-button  size="small"  type="text"   @click="showMonitor(scope.$index, dataArr)">编辑</el-button> |
                            <router-link  :to="'/sites/sitesRule/'+scope.row.id+'_rule'">报警规则</router-link> |
                            <router-link  :to="'/sites/sitesRule/'+scope.row.id+'_charts'">监控图表</router-link>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="pageSIzeblock">
                    <div class="pullright">
                        <el-pagination @size-change="handleSizeChange"  @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagesz" layout="total, sizes, prev, pager, next, jumper" :total="totalSize">
                        </el-pagination>
                    </div>
                    <div class="pullLeft">
                        <el-button  size="small" name="button-del" @click="delAll()" :disabled="pdisabled">批量删除</el-button>
                        <el-button  size="small" ><router-link  :to="'/sites/sitesallRule/'">查看全部规则</router-link> </el-button>

                    </div>
                </div>

            </section>


            <el-dialog :title="monitorTitle" :visible.sync="creatDialogVislble" class="customDialog team" :lock-scroll="false">
                <div class="scoreContainer tagCategory">
                    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
                        <el-form-item label="站点类型" prop="type">
                            <el-select v-model="ruleForm.type" placeholder="请选择站点类型" @change="trequired">
                                <el-option label="HTTP" value="HTTP"></el-option>
                                <el-option label="PING" value="PING"></el-option>
                                <el-option label="TCP" value="TCP"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="项目名称" prop="projectName">
                            <el-input v-model="ruleForm.projectName" ></el-input>
                        </el-form-item>
                        <el-form-item label="监控点名称" prop="name">
                            <el-input v-model="ruleForm.name"></el-input>
                        </el-form-item>
                        <el-form-item label="监控地址" prop="address">
                            <el-input v-model="ruleForm.address" placeholder="HTTP类型需要加上http://"></el-input>
                        </el-form-item>
                        <el-form-item label="监控频率" prop="frequency">
                            <el-select v-model="ruleForm.frequency" placeholder="请选择监控频率">
                                <el-option label="1分钟" value="1"></el-option>
                                <el-option label="10分钟" value="10"></el-option>
                                <el-option label="15分钟" value="15"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="连续异常报警" prop="number" :rules="[{ required: true, message: '请选择次数'}]">
                            <el-select v-model="ruleForm.number" placeholder="次数" >
                                <el-option label="1" value="1"></el-option>
                                <el-option label="3" value="3"></el-option>
                                <el-option label="5" value="5"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="请求方法" prop="rqType" v-show="ruleForm.type === 'HTTP'" :rules="[{ required: httpReRequired, message: '请选择请求方式'}]">
                            <el-radio-group v-model="ruleForm.rqType">
                            <el-radio label="GET "></el-radio>
                            <el-radio label="POST"></el-radio>
                            </el-radio-group>
                        </el-form-item>

                        <el-form-item label="负责人信息" prop="principal">
                             <el-input v-model="ruleForm.principal"></el-input>
                        </el-form-item>

                        <el-form-item label="端口号" prop="port"  v-show="ruleForm.type === 'TCP'" :rules="[{ required: tcpReRequired, message: '请输入端口号'}]">
                            <el-input v-model="ruleForm.port" type="number"></el-input>
                        </el-form-item>

                        <el-form-item label="联系组" prop="ttUser" multiple :rules="[{ required: false, message: '联系组'}]">
                            <el-checkbox-group v-model="ruleForm.ttUser">
                                <el-checkbox :label="item.id" v-for="(item,index) in groupOption" :key="index" >{{item.name}}</el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-form>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="creatDialogVislble = false">取 消</el-button>
                    <el-button type="primary" @click="creatSubmit('ruleForm')">确 定</el-button>
                </span>
            </el-dialog>
        </div>

    </div>
</template>

<script>
import { getList, modifySiteConf, deleteBatchSiteConf, queryGroupList, querySiteConfByName } from '@/api/getData'
export default {
  data() {
    var nameValidate = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入站点名称'))
      } else if (value.trim().length < 2 || value.trim() > 21) {
        callback(new Error('长度在 2 到 20 个字符'))
      } else {
        var listQuery = { name: value, id: this.ruleForm.id }
        querySiteConfByName(listQuery).then(response => {
          var has = response.data.has
          if (has) {
            callback(new Error('站点已经存在'))
          } else {
            callback()
          }
        })
      }
    }
    return {
      dataArr: null,
      monitorTitle: '',
      dataAddress: [],
      listLoading: true,
      isNotPermission: '',
      advancedSettings: false,
      httpReRequired: false,
      tcpReRequired: false,
      pdisabled: true,
      typeDisabled: false,
      creatDialogVislble: false,
      currentSetting: '',
      currentPage: 1,
      pagesz: 10,
      totalSize: 0,
      hightsetting: false,
      hasError: false,
      selected: '',
      tpvalue: '',
      addrinput: '',
      projectName: '',
      groupOption: [],
      multipleSelection: [],
      typeMonitorOptions: [{
        tpvalue: '全部类型'
      }, {
        tpvalue: 'HTTP'
      }, {
        tpvalue: 'TCP'
      }, {
        tpvalue: 'PING'
      }],
      ruleForm: {
        projectName: '',
        type: '',
        name: '',
        rqType: '',
        roleIds: '',
        principal: '',
        frequency: '',
        number: '',
        address: '',
        cookie: '',
        port: '',
        toUser: '',
        ttUser: [],
        httpHeader: '',
        httpVerifyName: '',
        httpVerifyPassword: ''
      },
      rules: {
        type: [
          { required: true, message: '请选择站点类型', trigger: 'change' }
        ],
        name: [
          { validator: nameValidate, required: true, trigger: 'blur' }
        ],
        projectName: [
          { required: true, message: '请输入项目名称', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入监控地址', trigger: 'blur' }
        ],
        frequency: [
          { required: true, message: '请选择监控频率', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.siteconfList(1, 'refresh', null, null, this.pagesz)
  },
  methods: {
    siteconfList(curr, t, addr, projectName, size) {
      this.listLoading = true
      if (size === undefined) {
        size = 10
      }
      if (t === '全部类型' || t === 'refresh') {
        if (t === 'refresh') {
          this.tpvalue = ''
        }
        t = undefined
      }
      var listQuery = { type: t, currPage: curr, address: addr, projectName: projectName, pageSize: size }
      getList(listQuery).then(response => {
        this.dataArr = response.data.data
        this.listLoading = false
        this.totalSize = response.data.totalRows
        this.currentPage = curr
        this.pagesz = size
        if (this.dataArr.length) {
          this.dataArr.forEach(function(element) {
            if (element.status === 0) {
              element.status = '正常'
            } else if (element.status === 1) {
              element.status = '异常'
              this.hasError = true
            } else {
              element.status = '未知'
            }
          }, this)
        }
      })
      queryGroupList().then(response => {
        this.groupOption = response.data.data
      })
    },
    showMonitor(index, data) {
      console.log(this.pagesz)
      var bb = []
      var _this = this
      this.creatDialogVislble = true
      if (data !== undefined) {
        if (data[index].type === 'HTTP') {
          this.httpReRequired = true
          this.tcpReRequired = false
        } else if (data[index].type === 'TCP') {
          this.tcpReRequired = true
          this.httpReRequired = false
        } else {
          this.httpReRequired = false
          this.tcpReRequired = false
        }
        this.typeDisabled = true
        this.monitorTitle = '修改监控点'
        this.ruleForm = {
          projectName: data[index].projectName,
          type: data[index].type,
          id: data[index].id,
          name: data[index].name,
          rqType: data[index].rqType,
          frequency: data[index].frequency,
          number: data[index].number,
          port: data[index].port,
          address: data[index].address,
          cookie: data[index].cookie,
          roleIds: data[index].roleIds,
          principal: data[index].principal,
          toUser: '',
          ttUser: [],
          httpHeader: data[index].httpHeader,
          httpVerifyName: data[index].httpVerifyName,
          httpVerifyPassword: data[index].httpVerifyPassword
        }
        if (data[index].roleIds !== undefined && data[index].roleIds !== null) bb = data[index].roleIds.split(',')
        bb.map(function(numberString) {
          return _this.ruleForm.ttUser.push(parseInt(numberString))
        })
      } else {
        this.typeDisabled = false
        this.monitorTitle = '创建监控点'
        this.ruleForm = {
          projectName: '',
          type: '',
          name: '',
          rqType: '',
          frequency: '',
          number: '',
          address: '',
          cookie: '',
          roleIds: '',
          principal: '',
          toUser: '',
          ttUser: [],
          httpHeader: '',
          httpVerifyName: '',
          httpVerifyPassword: ''
        }
      }
    },
    creatSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var tip = '确认创建站点？'
          if (this.ruleForm.id !== undefined) {
            tip = '确认修改站点？'
          }
          this.$confirm(tip, '提示', {
            type: 'warning'
          })
          .then(_ => {
            this.ruleForm.roleIds = this.ruleForm.ttUser.join(',')
            modifySiteConf(this.ruleForm).then(response => {
              this.dataArr = response.data.data
              this.listLoading = false
              this.creatDialogVislble = false
              this.siteconfList(1, 'refresh', null, null, this.pagesz)
              this.$message({
                message: '操作成功!',
                type: 'success'
              })
            })
          })
        .catch(_ => {})
        }
      })
    },
    querySiteConfByName(name) {
      var listQuery = { name: name }
      var has = false
      querySiteConfByName(listQuery).then(response => {
        has = response.data.has
      })
      return has
    },
    sethigh() {
      this.hightsetting = true
    },
    handleSizeChange(val) {
      this.siteconfList(1, this.tpvalue, this.addrinput, this.projectName, val)
    },
    handleCurrentChange(val) {
      this.siteconfList(val, this.tpvalue, this.addrinput, this.projectName, this.pagesz)
    },
    delAll() {
      const idQuery = []
      this.multipleSelection.forEach(function(element) {
        idQuery.push(element.id)
      }, this)
      const obj = {
        ids: idQuery.join(',')
      }
      this.$confirm('确定要删除选中的数据？', '提示', {
        type: 'warning'
      })
      .then(_ => {
        deleteBatchSiteConf(obj).then(response => {
          console.log(response.data)
          this.siteconfList(1, 'refresh', null, null, this.pagesz)
          this.$message({
            message: '删除成功!',
            type: 'success'
          })
        })
      })
    .catch(_ => {})
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      if (this.multipleSelection.length > 0) {
        this.pdisabled = false
      } else {
        this.pdisabled = true
      }
    },
    trequired() {
      if (this.ruleForm.type === 'HTTP') {
        this.httpReRequired = true
        this.tcpReRequired = false
      } else if (this.ruleForm.type === 'TCP') {
        this.tcpReRequired = true
        this.httpReRequired = false
      } else {
        this.httpReRequired = false
        this.tcpReRequired = false
      }
    }
  }
}
</script>

<style lang="scss">
.detail-header{
    padding: 0 15px;
    margin-bottom: 10px;
    overflow: hidden;
    .console-title{
        padding: 16px 0px;
        min-height: 70px;
        border-bottom: 1px solid #eee;
        position: relative;
        h5{
            display: inline-block;
            text-indent: 8px;
            border-left: 2px solid #88B7E0;
            margin: 8px 0;
            margin-right: 8px;
            vertical-align: top;
        }
        .stayRight{
            position: absolute;
            top: 15px;
            right: 0;
            overflow: hidden;
            .refresh{
                float: left;
                margin-right: 10px;
                color: #333;
                border: 1px solid #ddd;
                background-color: #F7F7F7;
            }
            .creatSite{
                float: left;
            }
        }
    }
}
.searchSel{
    width: 150px;
    display: inline-block;
}
.searchIpt{
    width: 350px;
    display: inline-block;
}
.searchbtn{
    width: 100px;
    display: inline-block;
}
.searchBar{
    padding: 0 10px;
}
.tableMain{
    padding: 10px;
}
.typeform{
    display: inline;
    .form-control{
        border: none;
        padding: 0;
        box-shadow:none;
        display: inline;
        height:30px;
        width:60%;
    }
}
.spantype{
    display: inline;
}
.pageSIzeblock{
    overflow: hidden;
    padding: 10px 0;
    .pullright{
        float: right;
    }
}
.statusError{
    color: red;
}
</style>


